<template>
  <div class="file-type-management">
    <div class="toolbar" style="align-self: flex-end; margin-bottom: 18px">
      <a-space wrap>
        <a-button
          class="editable-add-btn"
          style="width: 100px"
          type="primary"
          @click="onClickSave"
          :disabled="loading"
          v-if="isEdit"
        >
          应用
        </a-button>
        <a-button
          class="editable-add-btn"
          style="width: 100px"
          @click="onClickAdd"
          :disabled="loading"
          v-else
        >
          新增
        </a-button>
      </a-space>
    </div>
    <a-table
      bordered
      :data-source="dataSource"
      :columns="columns"
      style="flex: 1"
      :pagination="false"
      :loading="loading"
      ref="instanceRef"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'suffixName'">
          <template v-if="record.isLocal">
            <a-input
              v-model:value="record.suffixName"
              @press-enter="onClickSave"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <a-button type="link" v-if="record.isLocal" @click="onDelete(record)">
            取消
          </a-button>
          <a-popconfirm title="确定删除?" @confirm="onDelete(record)" v-else>
            <a-button
              type="link"
              :loading="loadingDeleteId === record.key"
              :disabled="loadingDeleteId === record.key"
            >
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script setup>
import { computed, reactive, ref, onMounted } from 'vue'
import { message as Message } from 'ant-design-vue'
import { nanoid } from 'nanoid'
import ATable from '@/components/table.vue'
import { getFileFormatList, fileFormatAdd, fileFormatDelete } from '@/api/db.js'
/**
 * 数据查询
 */
async function update() {
  try {
    let result = await getFileFormatList()
    dataSourceRemote.value = (result?.data || []).map(
      ({ id, suffixNo, suffixName }) => {
        return {
          key: id,
          suffixNo,
          suffixName,
        }
      },
    )
  } catch (e) {}
}

onMounted(async () => {
  loading.value = true
  await update()
  loading.value = false
})

let columns = [
  {
    title: '文件后缀',
    dataIndex: 'suffixName',
  },
  {
    title: '系统编号',
    dataIndex: 'suffixNo',
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
]
let dataSourceRemote = ref([])
let dataSourceLocal = ref([])

let dataSource = computed(() => {
  return [...dataSourceLocal.value, ...dataSourceRemote.value]
})
/**
 * 事件
 */

let loading = ref(false)
let isEdit = ref(false)
function onClickAdd() {
  dataSourceLocal.value = [
    {
      key: nanoid(),
      suffixNo: '-',
      suffixName: '',
      isLocal: true,
    },
    ...dataSourceLocal.value,
  ]
  isEdit.value = true
  scrollToRow()
}
async function onClickSave() {
  loading.value = true
  try {
    let errors = (
      await Promise.all(
        dataSourceLocal.value.map(({ suffixName }) => {
          if (!suffixName) {
            let info = '文件后缀名不能为空'
            Message.error(info)
            throw info
          }

          let isSuffixName = dataSource.value.filter(
            item => item.suffixName === suffixName,
          )
          if (isSuffixName.length > 1) {
            let info = `文件后缀名"${suffixName}"已存在`
            Message.error(info)
            throw info
          }

          return fileFormatAdd({ suffixName })
            .then(result => {
              // if (!result.success) {
              //   return 'suffixName'
              // }
            })
            .catch(() => {
              return suffixName
            })
        }),
      )
    ).filter(suffixName => suffixName)

    let suffixNameFirst = dataSourceLocal.value?.[0]?.suffixName
    dataSourceLocal.value = dataSourceLocal.value.filter(({ suffixName }) =>
      errors.includes(suffixName),
    )
    if (errors.length === 0) {
      await update()
      scrollToRow(suffixNameFirst)
      isEdit.value = false
    }
  } catch (e) {
    console.log(e)
  }
  loading.value = false
}

let loadingDeleteId = ref(null)
let onDelete = async record => {
  if (record.isLocal) {
    dataSourceLocal.value = dataSourceLocal.value.filter(
      item => item.key !== record.key,
    )
    isEdit.value = false
  } else {
    loadingDeleteId.value = record.key
    try {
      await fileFormatDelete({ id: record.key })
      loading.value = true
      await update()
      loading.value = false
    } catch (e) {}
    loadingDeleteId.value = null
  }
}
/**
 * 滚动
 */
let instanceRef = ref()
function scrollToRow(suffixName) {
  let tableBody = instanceRef.value.$el.querySelector('.ant-table-body')
  if (tableBody) {
    if (suffixName) {
      let rowKey = dataSource.value.find(
        item => item.suffixName === suffixName,
      )?.key
      if (rowKey) {
        let rowElement = tableBody.querySelector(`[data-row-key="${rowKey}"]`)
        if (rowElement) {
          let tableBodyScrollTop = rowElement.offsetTop
          tableBody.scrollTop = tableBodyScrollTop
        }
      }
    } else {
      tableBody.scrollTop = 0
    }
  }
}
</script>
<style lang="less" scoped>
.file-type-management {
  background-color: #fff;
  padding: 16px 24px;
  display: flex;
  flex-direction: column;
  height: 100%;
}
</style>
